package com.eco.controller;

import com.eco.service.RedisService;
import com.eco.util.CaptchUtil;
import com.eco.util.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("captcha")
@CrossOrigin
public class CaptchaController {
    @Autowired
    CaptchUtil captchaUtil;

    @Autowired
    RedisService redisService;
    @RequestMapping("base")
    public Result getCaptcha(HttpServletResponse response) {
        String[] arr =  captchaUtil.getImge();
        String key = arr[0];
        String base64 = arr[1];
//        Cookie cookie = new Cookie("captchakey",key);
//        response.addCookie(cookie);
        return Result.success("已经获取验证码",key+"+data:image/jpeg;base64,"+base64);
    }

@RequestMapping("check")
    public Result checkCaptcha(HttpServletRequest request,@RequestParam("captchaCode") String captchaCode) {

        Cookie[] cookies = request.getCookies();
        String key = null;
        for(Cookie cookie:cookies) {
           if(cookie.getName().equalsIgnoreCase("captchakey")){
               key = cookie.getValue();
               break;
           }
        }
        if(key==null){
            return Result.fail(400,"请求参数异常");
        }
        String code = (String) redisService.get(key);
        if(code==null){
            return Result.fail(201,"验证码过期");
        }
        if(captchaCode.equalsIgnoreCase(code)) {
            return Result.success("验证码正确", true);
        }
        return Result.fail(400,"验证失败");
    }
}
























